<template>
  <div>
    <el-table :data="teachers" style="width: 100%" ref="table" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="教师ID"></el-table-column>
      <el-table-column prop="name" label="教师姓名"></el-table-column>
      <!-- 其他列 -->
    </el-table>
    <el-button type="primary" @click="confirmSelection">确认选择</el-button>
    <el-table :data="selectedTeachers" style="width: 100%" ref="table" >
      <el-table-column prop="teacherName" label="教师姓名"></el-table-column>
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <span v-if="scope.row.status === '1'">已选择</span>
          <span v-else>其他状态</span>
        </template>
      </el-table-column>
      <!-- 其他列 -->
    </el-table>
  </div>
  </template>
  <script>
  export default {
      data(){
          return{
              teachers:[],
              selectedTeachers:[],
              selectedTeacher:null,
              user:JSON.parse(localStorage.getItem('honey-user') ||('{}')),
          };
      },
      mounted(){
          this.fetchTeachers()
          this.fetchSelectedTeachers();
      },
      methods:{
            fetchTeachers(){
              this.$request.get('/select/teachers')
              .then(res=>{
              this.teachers=res.data
          })
          },
          fetchSelectedTeachers() {
            this.$request.get('/select/selectedTeacher',{params:{userId:this.user.id}})
        .then(res => {
            this.selectedTeachers=res.data
        })
        .catch(error => {
            console.error('Error:', error);
        });
          },

          handleSelectionChange(selection){
            if(selection.length>1){
                    // 清除多余的选择或者给出提示
                    this.$refs.table.clearSelection();
                    this.$message.warning('只能选择一个教师！');
            }else{
                this.selectedTeacher = selection.length > 0 ? selection[0] : null;
            }
          },
          confirmSelection(){
            if(this.selectedTeacher){
                const resData=[
                    this.selectedTeacher.id ,
                    this.user.id
                ]
            this.$request.post('/select/selectTeacher', resData)
            .then(res=>{
                this.$message.success('选择成功!')
                this.fetchSelectedTeachers();
            })
           }else{
            this.$message.warning('请选择一个教师!')
           }
          }
      },
  }
  </script>
  
  <style>
  
  </style>